﻿using System;
using WinRTFramework.Extensions;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace DPChangedExtension
{
	public sealed partial class DemoControl : UserControl
	{
		private bool showingMessage;
		public DemoControl()
		{
			this.InitializeComponent();

			this.RegisterDependencyPropertyChanged( () => DataContext, DataContextChangedHandler );
			this.RegisterDependencyPropertyChanged( () => Visibility, VisibilityChangedHandler );
			this.RegisterDependencyPropertyChanged( () => IsHitTestVisible, IsHitTestVisibleChangedHandler );
		}

		private void DataContextChangedHandler( DependencyPropertyChangedEventArgs obj )
		{
			DataContextOldTextBlock.Text = obj.OldValue == null ? "None" : obj.OldValue.ToString();
			DataContextNewTextBlock.Text = obj.NewValue == null ? "None" : obj.NewValue.ToString();
		}

		private void VisibilityChangedHandler( DependencyPropertyChangedEventArgs obj )
		{
			// MessageDialog throws an exception if you try to show more than one at a time
			if ( !showingMessage )
			{
				ShowMessage( string.Format( "Visibility changed from \"{0}\" to \"{1}\"", obj.OldValue, obj.NewValue ) );
			}
		}

		private void IsHitTestVisibleChangedHandler( DependencyPropertyChangedEventArgs obj )
		{
			IsHitTestVisibleOldValueTextBlock.Text = obj.OldValue == null ? "None" : obj.OldValue.ToString();
			IsHitTestVisibleNewValueTextBlock.Text = obj.NewValue == null ? "None" : obj.NewValue.ToString();
		}

		private async void ShowMessage( string message )
		{
			showingMessage = true;
			MessageDialog dialog = new MessageDialog( message, "Dependency Property Changed" );
			dialog.Commands.Add( new UICommand( "OK" ) );
			dialog.DefaultCommandIndex = 0;
			await dialog.ShowAsync();
			showingMessage = false;
		}
	}
}